package com.tcs.netty.code.decoder;

import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.tcs.util.protostuff.ProtostuffUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 解码器
 */
public class MyObjDecoder extends ByteToMessageDecoder {

    private final Logger logger = LoggerFactory.getLogger(MyObjDecoder.class);

    private Class genericClass;

    private MyObjDecoder(){}

    public MyObjDecoder(Class genericClass) {
        this.genericClass = genericClass;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() < 4) {
            return;
        }
        in.markReaderIndex();
        int dataLength = in.writerIndex();
        if (dataLength < 0) {
            ctx.close();
        }
        if (in.readableBytes() < dataLength) {
            logger.info(" if 不通过, 因为 readableBytes : {} < , datalength: {} " , in.readableBytes(), dataLength);
            in.resetReaderIndex();
        }
        byte[] data = new byte[dataLength];
        in.readBytes(data);
        logger.info("dataLeng: {} , cap: {} , readerIndex: {} , writerIndex: {} , data : {} " , dataLength, in.capacity() , in.readerIndex(), in.writerIndex() , data);
        Object obj = ProtostuffUtil.deserializer(data, genericClass);
        out.add(obj);
    }
}
